﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace blackhouse.BlackApart.Data.Caching {
	public class CachedFurnitureDataAccess : IFurnitureDataAccess {

		#region Fields

		private IFurnitureDataAccess decoratedDataAccess;
		private NemoCache cache;

		#endregion

		#region Constructors

		public CachedFurnitureDataAccess(IFurnitureDataAccess decoratedDataAccess, string connectionStringToDecoretedDb) {
			this.decoratedDataAccess = decoratedDataAccess;
			this.cache = new NemoCache(TimeSpan.FromMinutes(2), connectionStringToDecoretedDb);
		}

		#endregion

		#region Methods

		public int SaveFurniture(int id, string name, string description, int sort, string imageName, byte[] imageData) {
			this.cache.TouchTimes();
			return this.SaveFurniture(id, name, description, sort, imageName, imageData);
		}

		public bool AddFurnitureToApartment(int furnitureId, int apartmentId) {
			this.cache.TouchTimes();
			return this.AddFurnitureToApartment(furnitureId, apartmentId);
		}

		public FurnitureData ReadFurniture(int furnitureId, string language) {
			cache.Reset();
			cache.SetDependencyTables("T99");
			cache.SetParameters(furnitureId, language);
			cache.SetKey("ReadFurniture");
			FurnitureData data = cache.GetData<FurnitureData>();
			if (data.Id == 0) {
				data = this.decoratedDataAccess.ReadFurniture(furnitureId, language);
				cache.SetCaching(data);
			}
			return data;
		}

		public FurnitureData[] GetApartmentFurnitures(int apartmentId, string language) {
			cache.Reset();
			cache.SetDependencyTables("T19", "T28_T99", "T99");
			cache.SetParameters(apartmentId, language);
			cache.SetKey("GetApartmentFurnitures");
			FurnitureData[] data = cache.GetData<FurnitureData[]>();
			if (data == null) {
				data = this.decoratedDataAccess.GetApartmentFurnitures(apartmentId, language);
				cache.SetCaching(data);
			}
			return data;
		}

		public FurnitureData[] GetApartmentTypeFurnitures(int apartmentTypeId, string language) {
			cache.Reset();
			cache.SetDependencyTables("T28_T99", "T99");
			cache.SetParameters(apartmentTypeId, language);
			cache.SetKey("GetApartmentTypeFurnitures");
			FurnitureData[] data = cache.GetData<FurnitureData[]>();
			if (data == null) {
				data = this.decoratedDataAccess.GetApartmentTypeFurnitures(apartmentTypeId, language);
				cache.SetCaching(data);
			}
			return data;
		}

		#endregion

	}
}
